/*
 * @Author: zhang zhijiang 2824735304@qq.com
 * @Date: 2025-04-16 17:06:17
 * @LastEditors: zhang zhijiang 2824735304@qq.com
 * @LastEditTime: 2025-04-17 17:29:25
 * @FilePath: /linux/test_4_16/udpclient.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include <iostream>
#include <string>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include<strings.h>
#include<arpa/inet.h>
#include<memory>
#include<unistd.h>
#include<pthread.h>
using namespace std;
static int Size = 1024;
struct threaddate
{
    struct sockaddr_in server;
    uint16_t sockfd;
};
void* recvmesg(void* args)//将收到的信息在error中进行输出
{
    threaddate* td = static_cast<threaddate*> (args);
    while(true)
    {
        char* buffer[Size];
        socklen_t len = sizeof(td->server);
        ssize_t s =  recvfrom(td->sockfd,buffer,Size-1,0,(sockaddr*)&td->server,&len);
        buffer[s] = 0;
        cerr<<buffer<<endl;
    }

}

void* sendmesg(void* args)
{
    threaddate* td = static_cast<threaddate*> (args);

    while(true)
    {
        string message;
        cout<<"please enter@"<<endl;
        getline(cin,message);
        socklen_t len = sizeof(td->server);
        sendto(td->sockfd,message.c_str(),message.size(),0,(sockaddr*)&td->server,len);
    }

}
int main(int argc,char* argv[])
{
    //不需要手动绑定IP地址
    if(argc!=3)
    {
    cout<< "right usage :"<< argv[0]<<"IP地址" <<"端口号"<<endl;
    }
    threaddate td; // 这里没有分配内存，直接解引用就会报错，
     td.sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(td.sockfd<0)
    exit(1);
    bzero(&td.server,sizeof(td.server));
    uint16_t port = atoi(argv[2]);
    string sendip = argv[1];
    td.server.sin_addr.s_addr = inet_addr(sendip.c_str());
    td.server.sin_port = htons(port);
    td.server.sin_family = AF_INET;
    pthread_t recv,send;
    pthread_create(&recv,nullptr,recvmesg,&td);
    pthread_create(&send,nullptr,sendmesg,&td);
    
    pthread_join(recv,nullptr);
    pthread_join(send,nullptr);
    close(td.sockfd);
    return 0;
}